//
//  MBThumbnailCache.m
//  Meboo
//
//  Created by kyo on 2023/11/15.
//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface MBThumbnailCache : NSObject

@end

@implementation MBThumbnailCache

+ (instancetype)sharedCache {
    static MBThumbnailCache *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MBThumbnailCache alloc] init];
    });
    return sharedInstance;
}

//获取视频的缩略图(第一帧)
- (UIImage *)getThumbnailImage:(NSString *)videoUrl {
    UIImage *theImage = nil;
     AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:videoUrl] options:nil];
     AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
     generator.appliesPreferredTrackTransform = YES;
     NSError *err = NULL;
     CMTime time = CMTimeMake(1, 60);
     CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];

     theImage = [[UIImage alloc] initWithCGImage:imgRef];
     CGImageRelease(imgRef);
     return theImage;
}

//存储7天 30天? 这里暂时存30天
- (void)setThumbnailImage:(UIImage *)image forKey:(NSString *)key {
    NSData *imageData = UIImagePNGRepresentation(image);
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:imageData forKey:key];
    NSTimeInterval expiration = 60*60*24*30;
    [defaults setObject:[NSDate dateWithTimeIntervalSinceNow:expiration] forKey:[NSString stringWithFormat:@"%@_expiration", key]];
    [defaults synchronize];
}

//根据key值取图片
- (UIImage *)getThumbnailImageForKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *expirationDate = [defaults objectForKey:[NSString stringWithFormat:@"%@_expiration", key]];
    if (expirationDate && [expirationDate compare:[NSDate date]] == NSOrderedDescending) {
        NSData *imageData = [defaults objectForKey:key];
        UIImage *image = [UIImage imageWithData:imageData];
        return image;
    } else {
        [defaults removeObjectForKey:key];
        [defaults removeObjectForKey:[NSString stringWithFormat:@"%@_expiration", key]];
        [defaults synchronize];
        return nil;
    }
}

@end
